import sys
import time
import unittest
from test import test_support
from nirvanix import Nirvanix
from nirvanix import Session
from nirvanix import NirvanixUploader
from nirvanix import NirvanixDownloader
import nirvanixutils

"""
To run the Unit Tests change the values below with the real values from your account. This
is required to run the unit tests.  You can get this information at http://nmp.nirvanix.com
"""

appKey = "APPKEY"
appName = "APPNAME"
masterUsername = "MASTERACCT"
masterPassword = "MASTERPASS"
childUsername = "CHILDACCT"
childPassword = "CHILDPASS"


class AuthenticationTests(unittest.TestCase):

	# Define setUp and tearDown only if needed
	def test_login(self):
		session = Session(appKey, masterUsername, masterPassword)
		assert(session.sessionToken)

	def test_login_failed(self):
		try:
			session = Session(appKey, masterUsername, "x")
		except nirvanixutils.NirvanixException, e:
			if e.code != 80001:
				raise e
			# Expected exception; passed test
		else:
			raise

	def test_logout(self):
		session = Session(appKey, masterUsername, masterPassword)
		del session

class IMFSTests(unittest.TestCase):

	# call create folder
	def test_createfolder(self):
		session = Session(appKey, masterUsername, masterPassword)
		imfs = Nirvanix('IMFS', session)
		foldername = '/test_folder_python_unique'
		options = {'folderPath':foldername}
		
		try:
			doc = imfs.DeleteFolders(options,False)
		except nirvanixutils.NirvanixException:
			print "Folder delete failed, first run of unit tests?"
		# after the folder has been removed try creating it. If an error occurs an exception
		# will be raised for createfolders.
		doc = imfs.CreateFolders(options,False)

	# call list folder and verify at least one sub folder exists.
	def test_listfolder(self):
		session = Session(appKey, masterUsername, masterPassword)
		imfs = Nirvanix('IMFS', session)
		options = {'folderPath':'/','pageNumber':'1','pageSize':'500'}
		doc = imfs.ListFolder(options,False)
		#print doc.toprettyxml()
		folderCount = doc.getElementsByTagName("TotalFolderCount")[0].childNodes[0].data
		#print 'Count: ' + folderCount
		assert(int(folderCount) > 0)

class SharingTests(unittest.TestCase):

	# call createhosteditem and verify the download link is returned (could expand to verify file contents).
	def test_createhosteditem(self):
		session = Session(appKey, masterUsername, masterPassword)
		# setup a file that we can host.
		uploader = NirvanixUploader(session, False)
		uploader.uploadfile('uploadtest.txt', '/sharetest/', 'sharetest.txt', overwrite=True)

		sharing = Nirvanix('Sharing', session);
		options = {'sharePath':'/sharetest/sharetest.txt'}
		doc = sharing.CreateHostedItem(options,False)
		#print doc.toprettyxml()
		downloadLink = doc.getElementsByTagName("DownloadLink")[0].childNodes[0].data
		assert(downloadLink != '')
		imfs = Nirvanix('IMFS', session);
		options = {'filepath':'/sharetest/sharetest.txt'}
		# Remove the file for the next test.
		imfs.deletefiles(options,False)

class MetadataTests(unittest.TestCase):

	# call getmetadata to verify the metadata on a file.
	def test_getmetadata(self):
		session = Session(appKey, masterUsername, masterPassword)
		# setup a file that we can host.
		uploader = NirvanixUploader(session, False)
		uploader.uploadfile('uploadtest.txt', '/metadatatest/', 'metadatatest.txt',overwrite=True)
		uploader.uploadfile('uploadtest.txt', '/metadatatest/', 'metadatatest2.txt',overwrite=True)

		metadata = Nirvanix('Metadata', session);
		# set some data first
		options = {'path':'/metadatatest/metadatatest.txt', 'metadata':['datatest:testvalue', 'datatest2:testvalue2']}
		doc = metadata.setMetadata(options,False)

		options = {'path':'/metadatatest/metadatatest.txt'}
		doc = metadata.getMetadata(options,False)
		#print doc.toprettyxml()
		data = doc.getElementsByTagName("Type")[0].childNodes[0].data
		assert(data == 'datatest')


class TransferTests(unittest.TestCase):

	# Upload test
	def test_1_upload(self):
		print "\r"
		session = Session(appKey, masterUsername, masterPassword)
		uploader = NirvanixUploader(session, True)
		uploader.uploadfile('uploadtest.txt', '/uptest/', 'uploadtest.txt', overwrite=True)
		print "\r\nUpload Test Complete."

	# Upload test CallbackURL
	def test_1_2_upload(self):
		print "\r"
		session = Session(appKey, masterUsername, masterPassword)
		uploader = NirvanixUploader(session, True)
		uploader.uploadfile('uploadtest.txt', '/uptest/', 'uploadtest.txt', callbackURL='http://www.nirvanixtest.com/writelog.php?pythontest=unittest15', overwrite=True)
		print "\r\nUpload Test Complete."

	# Upload test
	def test_2_upload_exclude_nodes(self):
		print "\r"
		session = Session(appKey, masterUsername, masterPassword)
		uploader = NirvanixUploader(session, True)
		uploader.uploadfile('uploadtest.txt', '/uptest/', 'uploadtest.txt', ['node2', 'node3', 'node4'], overwrite=True, iprestricted= False)
		print "\r\nExcluded Nodes Upload Test Complete."
	
	# Download test
	def test_3_download(self):
		print "\r"
		session = Session(appKey, masterUsername, masterPassword)
		downloader = NirvanixDownloader(session, True)
		downloader.downloadfile('uploadtest.txt', '/uptest/uploadtest.txt')
		print "\r\nDownload Test Complete."

	# Download test
	def test_4_multithread_download(self):
		print "\r"
		session = Session(appKey, masterUsername, masterPassword)
		downloader = NirvanixDownloader(session, True, 2)
		# this should be modified to use a larger file for a more realistic test but is kept small to keep the test fast.
		downloader.downloadfile('uploadtest.txt', '/uptest/uploadtest.txt')
		print "\r\nMultithread Download Test Complete."

	# Download test
	def test_5_download_exclude_nodes(self):
		print "\r"
		session = Session(appKey, masterUsername, masterPassword)
		downloader = NirvanixDownloader(session, True)
		downloader.downloadfile('uploadtest.txt', '/uptest/uploadtest.txt', ['node2', 'node3', 'node4'])
		print "\r\nExcluded Nodes Download Test Complete."


if __name__ == "__main__":
	unittest.main()